String formatting in Go

Creating dynamic strings

Created: August 16th 2019
Updated: December 7th 2019
Connect with us on
image
image

String formatting is an incredibly useful tool for building dynamic strings in Go programs. It will allow you to build strings using variable's as input.

Definitions

Some terms to help you navigate the post

String Formatting

The process of dynamically building strings based on variables and preset values. For example, lets say you are bulding a client dashboard that displays a welcome message. For this you might want to create a greeting that is along the lines of:

Hello <name> The weather today is <current_temperature> degrees. You have <email_count> new emails..

To do this you could do:

name := "John Smith" // A dummy name
emailCount := 3 // A representation of users # of new emails
currentTemperature := 20.3567 // A representation of the current temperature in celsius
fmt.Printf("Hello, %s The weather today is %f degrees. You have %d new emails.",
    name, currentTemperature, emailCount)

Note that fmt.Printf() can be used to format and immediately print strings. You can also use fmt.Sprintf() to just build the string and use it later.

For example:

name := "John Smith" // A dummy name
emailCount := 3 // A representation of users # of new emails
currentTemperature := 20.3567 // A representation of the current temperature in celsius
// Create greeting string to be used later
greeting := fmt.Sprintf("Hello, %s The weather today is %b degrees. You have %d new emails.",
    name, currentTemperature, emailCount)

Usage

All of the code in the demo requires no external dependencies, it can be run by using one of two methods:

  1. You can run the file directly via go run stringFormatting.go
  2. You can compile the file using go build stringFormatting.go then run the resulting binary (.exe on windows, and regular binary on mac/linux).

Real World Applications

String formatting is used all over the place to do everything from welcome messages to system and program information output messages.

Files

stringFormattingDemo.go

package main
import "fmt" // More info about % operators can be found here: https://golang.org/pkg/fmt/

// Coin is a struct to represent coins
type Coin struct {
    value int // How much the coin is worth in cents as an int
    name string // The colloquial name of the coin
}

// A function showing off print formatting with
func main() {

    // Example of formatting with ints
    number := 3
    fmt.Printf("Value of number: %d", number)

    // Example of formatting with floats
    pi := 3.14159
    fmt.Printf("\nValue of pi: %f", pi)

    // Example of formatting with strings
    greeting := "Hello World!" fmt.Printf("\nValue of greeting: %s", greeting)

    // Example of formatting with struct instances
    quarter := Coin{value: 25, name: "Quarter"} // Printing a struct instance prints it's values
    fmt.Printf("\nValues of a quarter: %v\nValues of a quarter with field names: %+v", quarter, quarter)

    // Example of printing what variables types are
    fmt.Printf("\nThe types of number, greeting and quater are %T, %T, and %T", number, greeting, quarter)
}

Thank you for your support!

Be sure to share the post if it was helpful!